import { useRef, useState } from 'react'
import { Group, Layer, Line, Rect, Stage, Transformer } from 'react-konva'

const trAttrs = {
  rotation: 45,
  scaleX: 0.9999999999999859,
  scaleY: 1.0000000000000226,
  skewX: -1.8873791418627503e-15,
  skewY: 0,
  x: 1206.2041153994471,
  y: 424.70894380558326
}
export default function View() {
  const [selectedShape, setSelectedShape] = useState(null)
  const stageRef = useRef(null)
  const groupRef = useRef(null)
  const transformerRef = useRef(null)

  const handleStageClick = e => {
    // 如果点击的是空白区域，取消选中
    if (e.target === e.target.getStage()) {
      setSelectedShape(null)
      return
    }

    // 如果点击的是矩形，选中它
    if (e.target.nodeType === 'Shape') {
      setSelectedShape(groupRef.current)
    }
  }

  return (
    <Stage width={window.innerWidth} height={window.innerHeight} ref={stageRef} onClick={handleStageClick}>
      <Layer>
        <Group
          ref={groupRef}
          draggable
          onDragEnd={e => {
            console.log('🚀 ~ View ~ e:', e.target.attrs)
          }}
          onTransformEnd={e => {
            console.log('🚀 ~ View ~ e:', e.target.attrs.rotation)
          }}
        >
          <Rect x={0} y={0} scaleX={1} scaleY={1} width={200} height={200} fill='red' />
          <Rect x={200} y={200} scaleX={1} scaleY={1} width={200} height={200} fill='yellow' />
          <Line
            {...trAttrs}
            tension={0.5}
            lineCap='round'
            lineJoin='round'
            points={[500, 500, 600, 600]}
            stroke={'red'}
            strokeWidth={10}
          />
        </Group>

        {selectedShape && (
          <Transformer
            ref={transformerRef}
            boundBoxFunc={(oldBox, newBox) => {
              // 限制最小尺寸
              if (newBox.width < 5 || newBox.height < 5) {
                return oldBox
              }
              return newBox
            }}
            nodes={[selectedShape]}
          />
        )}
      </Layer>
    </Stage>
  )
}
